<?php

namespace app\admin\controller\exchange;

use app\common\controller\Backend;
use think\Session;
use Yeepay\Yop\Sdk\V1\YopConfig;
use Yeepay\Yop\Sdk\V1\YopRequest;
use Yeepay\Yop\Sdk\V1\YopRsaClient;
use Yeepay\Yop\Sdk\V1\Util\YopSignUtils;
use sandpay\HmPayClient;
use sandpay\PosHmPayClient;
use app\admin\model\Sandmerch;
use app\admin\model\exchange\Ordergas;
use app\admin\model\exchange\Ordergoods;
use app\admin\model\exchange\OrderGasInfo;
use app\admin\model\exchange\OrderGoodsInfo;
use app\admin\model\exchange\Order;
use Xpyun\model\PrintRequest;
use Xpyun\service\PrintService;
use Xpyun\util\NoteFormatter;
use app\admin\model\gas\Gasset;
use app\admin\model\gas\Gasgun;
use app\admin\model\gas\Gasoil;
use app\admin\model\goods_manage\Goods;
use app\admin\model\Printer;
use app\admin\model\system_config\Storeset;
use app\common\model\StoreConfig;
/**
 * 充值订单
 *
 * @icon fa fa-circle-o
 */
class Orderrecharge extends Backend
{

    /**
     * Orderrecharge模型对象
     * @var \app\admin\model\exchange\Orderrecharge
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\exchange\Orderrecharge;
        $this->view->assign("isPayList", $this->model->getIsPayList());
        $this->view->assign("payTypeList", $this->model->getPayTypeList());
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("sourceTypeList", $this->model->getSourceTypeList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

   /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
    	 $user_info = Session::get('admin');//获取当前登录用户信息
    	 $llimitorder = StoreConfig::where('name','order_limit')->where('store_no',$user_info['store_no'])->find();
    	$wheretime = [];
    	if($llimitorder['value'])
    	{
    		$limittime =  strtotime('-'.$llimitorder['value'].' hours');
    		$wheretime['createtime'] = array('gt',$limittime);
    	}

        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->where('store_no',$user_info['store_no'])
            ->where('is_delete',0)
            ->where($wheretime)
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
          foreach ($list as $index => $item) {
         	
         	$limittime =  strtotime(date('Y-m-d',time()));
         	$item->draw = 0;
         	if($limittime>$item->createtime)$item->draw = 1;
        }
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }
    
      /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function show($ids = null)
    {
        $row = $this->model->get($ids);
//        var_dump($row);die;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }

    	$yee= \app\admin\model\Yee::where('store_no',$row->store_no)->find();
    	$orderinfo =Order::where('order_no', $row->order_no)->find();
        	if($row->channel == 'YeeBao')
    		{
    			
    			    $response = $this->channelyeerefund($yee,$row->order_no,$orderinfo['total_pay_price']);
			        if(isset($response->result->code) && $response->result->code == 'OPR00000')
			        {
			        	$this->success('退款成功');
			        }
                    $this->error('退款失败');
    		}
    		
//  		if($row->channel == 'YeeBao')
//  		{
//  			
//  			    $response = $this->channelyeerefund($yee,$row->order_no,$row->total_pay_price);
//			        if(isset($response->result->code) && $response->result->code == 'OPR00000')
//			        {
//			        	$this->success('退款成功');
//			        }
//                 
//  		}
    		if($row->channel == 'sandPay'&&$row->pay_way != 3)
    		{
    			    $jsonResp ='';
    			    $jsonResp = $this->channelsandrefund($row->order_no,$row->createtime,$orderinfo['total_pay_price']);
    		
			        if(isset($jsonResp['code']) && $jsonResp['code'] == '200')
			        {
			        	$data = json_decode($jsonResp['data'], JSON_UNESCAPED_UNICODE);
			        
                        if($data['sub_code'] == 'REFUND_SUCCESS')
                        {
                        	Order::where('order_no', $row->order_no)->update(['is_pay' => 1,'status'=> 2]);
//                          Ordergas::where('order_no', $row->order_no)->update(['is_pay'=>1,'status'=> 2]);
//      			        Ordergoods::where('order_no', $row->order_no)->update(['is_pay'=>1,'status'=> 2]);
        			        $params['is_pay']=1;
        			        $params['status']=2;
                             $row->save($params);
        			        
        			        $this->success('退款成功');
                        }
                        $this->error('退款失败');
			        }
		             $this->error('退款失败');
			        
    		}
    		
    		if($row->channel == 'sandPay'&&$row->pay_way == 3)
    		{
    			    $jsonResp ='';
    			    $jsonResp = $this->channelsandposrefund($row->bank_no,$row->createtime,$orderinfo['total_pay_price']);
    		
			          if(isset($jsonResp['code']) && $jsonResp['code'] == '200')
			        {
			        	$data = json_decode($jsonResp['data'], JSON_UNESCAPED_UNICODE);
			 
                        if($data['sub_code'] == 'REFUND_SUCCESS')
                        {
                        	Order::where('order_no', $row->order_no)->update(['is_pay' => 1,'status'=> 2]);
//                          Ordergas::where('order_no', $row->order_no)->update(['is_pay'=>1,'status'=> 2]);
//      			        Ordergoods::where('order_no', $row->order_no)->update(['is_pay'=>1,'status'=> 2]);
        			        $params['is_pay']=1;
        			        $params['status']=2;
                             $row->save($params);
        			        
        			        $this->success('退款成功');
                        }
                        $this->error('退款失败');
			        }
		             $this->error('退款失败');
			        
    		}
    		if($row->channel == 'cash')
    		{
    			Order::where('order_no', $row->order_no)->update(['is_pay' => 1,'status'=> 2]);

        		$params['is_pay']=1;
        		$params['status']=2;
                $row->save($params);
        			        
        		$this->success('退款成功');
    		}
    		
    		
        $this->error('退款失败');
    }
    
         /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function deleteshow($ids = null)
    {
        $row = $this->model->get($ids);
//        var_dump($row);die;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }

        	if($row->is_delete == 0)
    		{
    			$params['is_delete']=1;
                $row->save($params);
    			$this->success('删除成功');
    		}
    		
    		
        $this->error('删除失败');
    }
          /**
     * 打印小票
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function print($ids = null)
    {
        $row = $this->model->get($ids);
//        var_dump($row);die;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }

        $this->eightprint($row->order_no,$row->store_no,$row->id);
    	$this->success('打印成功');
    }
    public function channelyeerefund($yee,$osn,$total_pay_price)
    {
    	  /*商户私钥*/
			        $private_key ="MIIEugIBADANBgkqhkiG9w0BAQEFAASCBKQwggSgAgEAAoIBAQCQMqL/T97RhAophQNRzBwE+vU+59PzfkEzyLZwMaQTduHvdTl4fg6KZ6ATFUgECI2JLpZq3cyjVYSlM9H20bRpZSaoYmsYyNibpf2lg+bMg9G+bS6elHvFn0ZJ+aU40wyWqPjtdLB9JYLDbLVsb6SzHegWovWeWD7vUqCbPhDK24V///baX2zV4609kfa1iBGbynF/0nggHw3leeUW9F8E8twSEF15ObE8ShywOMvi578kv9PUNmSiq8gfc/t8dWVOzi4mbDje49MhxMbuopGv1kcvHBrThTeqQ2plhQSs63AbwLpe4WsZbcNvG9zpjuci8bK1+Z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KJuZsOGkqgmfkJhAOnC2wLPDMMFDXnWG+oPcI6bosyvM+I8FDqwE3VcbmFlEJPnC4hQvwK3JjAju6FGhDgoB98rihcaUlsJfoTvrSmkLAmQOH8DW+a0UVbcCMp7TtWgpC8UMT0adAb/4ngQhjYuED4pI=";
			
			        $request = new YopRequest("app_10088909942", $private_key);
			        $expireTime = date("yyyy-MM-dd HH:mm:ss", strtotime("+30 minute"));//过期时间
			        $client_ip = $_SERVER['REMOTE_ADDR'];
			        //加入请求参数
			        $request->addParam("parentMerchantNo",'10088970121');
			        $request->addParam("merchantNo",$yee['merchantNo']);
			        $request->addParam("orderId",$osn);
			        $request->addParam("refundRequestId",'YBRWQQH'.time());
			        $request->addParam("refundAmount",$total_pay_price);
			        $request->addParam("description",'用户申请退货并退款');
                    $request->addParam("notifyUrl",'https://store.leyinshuke.com/api/index/refundnotify');
			//      //提交Post请求
			        $response = YopRsaClient::post("/rest/v1.0/trade/refund", $request);
			        return $response;
    }
    
    public function channelsandrefund($osn,$createTime,$total_pay_price)
    {
    			    $user_info = Session::get('admin');//获取当前登录用户信息
    	            $sandmer = Sandmerch::where('store_no', $user_info['store_no'])->find();
    	  /*商户私钥*/
		           $request = new HmPayClient();

			        $url = $request->gatewayUrl;
			
			        $appId = '552021071325659';
			        $subAppId = $sandmer['sub_merchant_no'];
			        $method = "trade.refund";
			        $format = $request->format;
			        $charset = $request->charset;
			        $signType = $request->signType;
			        $version = $request->apiVersion;
			        $timestamp = date("Y-m-d h:i:s");
			        $nonce = $request->getRandStr(8);
			        $privateKey = $request->rsaPrivateKey;
			        //支付方式
		
			        $createIp = $_SERVER['REMOTE_ADDR'];//生产环境使用真实ip
			        $createTime = date("YmdHis",$createTime);

	
			        $outOrderNo = $osn;
			        //商户交易门店
			        $storeId = $sandmer['sand_store_no'];

			
			        $bizContent = $request->traderefund($createTime,$outOrderNo,$total_pay_price,$nonce,$storeId);
			        
			        $response = $request->execute($url, $request->request($appId, $subAppId, $method, $format, $charset, $signType, $timestamp, $nonce, $version, $bizContent, $privateKey));
			        
			        $jsonResp = json_decode($response, JSON_UNESCAPED_UNICODE);
			        return $jsonResp;
    }
      public function channelsandposrefund($osn,$createTime,$total_pay_price)
    {
    	
    	            $user_info = Session::get('admin');//获取当前登录用户信息
    	            $sandmer = Sandmerch::where('store_no', $user_info['store_no'])->find();
    	  /*商户私钥*/
		           $request = new HmPayClient();

			        $url = $request->gatewayUrl;
			
			        $appId = '552021071325659';
			        $subAppId = $sandmer['sub_merchant_no'];
			        $method = "trade.refund";
			        $format = $request->format;
			        $charset = $request->charset;
			        $signType = $request->signType;
			        $version = $request->apiVersion;
			        $timestamp = date("Y-m-d h:i:s");
			        $nonce = $request->getRandStr(8);
			        $privateKey = $request->rsaPrivateKey;
			        //支付方式
		
			        $createIp = $_SERVER['REMOTE_ADDR'];//生产环境使用真实ip
			        $createTime = date("YmdHis",$createTime);

	
			        $outOrderNo = $osn;
			        //商户交易门店
			        $storeId = $sandmer['sand_store_no'];

			
			        $bizContent = $request->tradeposrefund($createTime,$outOrderNo,$total_pay_price,$nonce,$storeId);
			        
			        $response = $request->execute($url, $request->request($appId, $subAppId, $method, $format, $charset, $signType, $timestamp, $nonce, $version, $bizContent, $privateKey));
			        
			        $jsonResp = json_decode($response, JSON_UNESCAPED_UNICODE);
			        return $jsonResp;
    }
        public function eightprint($osn,$store_no,$order_id)
    {
    	        /**
         * <BR>：换行符（同一行有闭合标签(如 </C>)则应放到闭合标签前面, 连续两个换行符<BR><BR>可以表示加一空行）
         *  <L></L>：左对齐
         *  <C></C>：居中对齐
         *  <R></R>：右对齐
         *  注意：同一行内容不能使用多种对齐方式，可通过补空格方式自定义对齐样式。
         *       58mm的机器，一行打印16个汉字，32个字母
         *       80mm的机器，一行打印24个汉字，48个字母
         *
         *  <N></N>：字体正常大小
         *  <HB></HB>：字体变高一倍
         *  <WB></WB>：字体变宽一倍
         *  <B></B>：字体放大一倍
         *  <CB></CB>：字体放大一倍居中
         *  <HB2></HB2>：字体变高二倍
         *  <WB2></WB2>：字体变宽二倍
         *  <B2></B2>：字体放大二倍
         *  <BOLD></BOLD>：字体加粗
         *  <IMG></IMG>：打印LOGO图片，需登录开放平台在【打印机管理=》设备管理】下通过设置LOGO功能进行上传。此处直接写入
         *             空标签, 如 <IMG></IMG> 即可, 具体可参考样例。
         *             图片宽度设置：可以通过 <IMG> 标签名称自定义，如 <IMG60> 表示宽度为60，相应的闭合标签 </IMG>
         *             不需要指定高度。<IMG> 标签不指定宽度默认为40，最小值为20，最大值为100
         *  <QR></QR>：二维码（标签内容是二维码值, 最大不能超过256个字符, 单个订单最多只能打印一个二维码）。
         *             二维码宽度设置：可以通过 <QR> 标签名称自定义，如 <QR180> 表示宽度为180，相应的闭合标签 </QR>
         *             不需要指定宽度。<QR> 标签不指定宽度默认为110，最小值为90，最大值为180
         *  <BARCODE></BARCODE>：条形码（标签内容是条形码值）
         */
//      $store_no = 1;
//      $osn = "2023020915430674623773";
        $storeinfo = Storeset::where('store_no',$store_no)->find();
        $order = Order::where('order_no', $osn)->find();
//      $ordergas = Ordergas::where('order_no', $osn)->find();
//      $ordergoods = Ordergoods::where('order_no', $osn)->find();
//      $ordergasinfo = OrderGasInfo::where('order_id', $ordergas['id'])->select();
//      $ordergoodsinfo = OrderGoodsInfo::where('order_id', $order_id)->select();
        $print = Printer::where('store_no', $store_no)->find();
        $printContent = "";

        $printContent = $printContent . "<C>" . "<B>".$storeinfo['store_name']."</B>" . "<BR></C>";
        $printContent = $printContent . "<BR>";
        $printContent = $printContent . "商品" . str_repeat(" ",15) . "数量" . str_repeat(" ", 2) . "单价" . str_repeat(" ", 2)
	            . "<BR>";
	    $printContent = $printContent . str_repeat("-", NoteFormatter::ROW_MAX_CHAR_LEN) . "<BR>";
	    $printContent = $printContent . NoteFormatter::formatPrintOrderItem('充值', 1,  $order['total_pay_price']);
	    $printContent = $printContent . str_repeat("-", NoteFormatter::ROW_MAX_CHAR_LEN) . "<BR>";

        	
        $printContent = $printContent . "<R>" . "合计：" . $order['total_pay_price'] . "元" . "<BR></R>";

        $printContent = $printContent . "<BR>";
        $printContent = $printContent . "<L>"
//          . "客户地址：" . "珠海市香洲区xx路xx号" . "<BR>"
            . "订单编号：" . $osn . "<BR>"
            . "下单时间：" . date("Y-m-d H:i") . "<BR>";
//          . "备注：" . "少放辣 不吃香菜" . "<BR>";

        $printContent = $printContent . "<C>"
            . "<QR>https://www.xpyun.net</QR>"
            . "</C>";


        $request = new PrintRequest();
        $request->generateSign();

        //*必填*：打印机编号
        $request->sn = $print['terminal_no'];

        //*必填*：打印内容,不能超过12K
        $request->content = $printContent;

        //打印份数，默认为1
        $request->copies = 1;

        //声音播放模式，0 为取消订单模式，1 为静音模式，2 为来单播放模式，3为有用户申请退单了。默认为 2 来单播放模式
        $request->voice = 1;
        //打印模式：
        //值为 0 或不指定则会检查打印机是否在线，如果不在线 则不生成打印订单，直接返回设备不在线状态码；如果在线则生成打印订单，并返回打印订单号。
        //值为 1不检查打印机是否在线，直接生成打印订单，并返回打印订单号。如果打印机不在线，订单将缓存在打印队列中，打印机正常在线时会自动打印。
        $request->mode = 1;
        
        
        //支付方式：
        //取值范围41~55：
        //支付宝 41、微信 42、云支付 43、银联刷卡 44、银联支付 45、会员卡消费 46、会员卡充值 47、翼支付 48、成功收款 49、嘉联支付 50、壹钱包 51、京东支付 52、快钱支付 53、威支付 54、享钱支付 55
        //仅用于支持金额播报的芯烨云打印机。
        $paytype = 41;
        if($order['pay_type'] == 1)$paytype = 42;
        if($order['pay_type'] == 2)$paytype = 41;
        if($order['pay_type'] == 3)$paytype = 44;

        $request->payType = $paytype;

        //支付与否：
        //取值范围59~61：
        //退款 59 到账 60 消费 61。
        //仅用于支持金额播报的芯烨云打印机。
        $request->payMode = 60;

        //支付金额：
        //最多允许保留2位小数。
        //仅用于支持金额播报的芯烨云打印机。
        $request->money = $order['total_pay_price'];
        
        
        $service = new PrintService();
        $result = $service->xpYunPrint($request);
        if($order['pay_type'] == 5)$service->xpYunControlBox($request);
//      echo json_encode($request);
//        print $result->content->code . "\n";
//        print $result->content->msg . "\n";
//
//        //data:正确返回订单编号
//        print $result->content->data . "\n";
    }
}
